/*
 * @Author: YNT 2501512800@qq.com
 * @Date: 2022-08-06 23:09:22
 * @LastEditors: YNT 2501512800@qq.com
 * @LastEditTime: 2022-10-14 11:35:17
 * @FilePath: \20220806后台\src\permission.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import router from "./router";
import store from "./store";
import axios from "axios";
import { Message } from "element-ui";
import NProgress from "nprogress"; // progress bar
import "nprogress/nprogress.css"; // progress bar style
import { getToken } from "@/utils/service/auth"; // get token from cookie
import getPageTitle from "@/utils/get-page-title";

NProgress.configure({ showSpinner: false }); // NProgress 配置

const whiteList = ["/login"]; // 无需重定向白名单

router.beforeEach(async (to, from, next) => {
  NProgress.start();
  document.title = getPageTitle(to.meta.title);
  const hasToken = getToken();
  if (hasToken) {
    if (to.path === "/login") {
      next({ path: "/" });
      NProgress.done();
    } else {
      //注：<store.getters.roles> 当前用户权限数组，
      // null 》代表用户未登录 Boolean(null) 》false，
      // [] 》已登录但权限列表为空 Boolean([]) 》true
      if (store.getters.roles) {
        next();
      } else {
        try {
          // 获取用户权限列表
          await store.dispatch("user/getInfo");
          let roles = [];
          // 根据 <roles> 生成其可访问的路由
          const accessRoutes = await store.dispatch(
            "permission/generateRoutes",
            roles
          );
          // 动态添加可访问的路由
          router.addRoutes(accessRoutes);
          // ...to, 以确保addRoutes是完整的
          // replace: true, 这样导航就不会留下历史记录
          // next()
          next({ ...to, replace: true });
        } catch (error) {
          // 异常，清除token 并回退至登录页面
          await store.dispatch("user/resetToken");
          next(`/login?redirect=${to.path}`);
          Message.error("登录状态失效，请重新登录！");
          NProgress.done();
        }
      }
    }
  } else {
    /* has no token*/
    if (whiteList.indexOf(to.path) !== -1) {
      // 白名单中路由无需重定向
      next();
    } else {
      // 其他没有访问权限的页面被重定向到登录页面
      next(`/login?redirect=${to.path}`);
      NProgress.done();
    }
  }
});

router.afterEach(() => {
  NProgress.done();
});
